package com.dianrui.fmi.update.utils;



import com.dianrui.fmi.Constant;
import com.dianrui.fmi.update.pojo.UpdateInfo;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * Created by Shelwee on 14-5-8.
 */
public class JSONHandler {

    public static UpdateInfo toUpdateInfo(InputStream is) throws Exception {
        if (is == null) {
            return null;
        }
        String byteData = new String(readStream(is));
        is.close();
        JSONObject jsonObject = new JSONObject(byteData);
        UpdateInfo updateInfo = new UpdateInfo();
        if (Constant.DATASUCCESS.equals(jsonObject.getString("status"))){
            updateInfo.setApkUrl(jsonObject.optJSONObject("data").optString("store_url"));
            updateInfo.setAppName(jsonObject.optJSONObject("data").optString("app_name"));
            updateInfo.setVersionCode(jsonObject.optJSONObject("data").optString("version_code"));
            updateInfo.setVersionName(jsonObject.optJSONObject("data").optString("version_name"));
            updateInfo.setExplain(jsonObject.optJSONObject("data").optString("explain"));
        }

        return updateInfo;
    }

    private static byte[] readStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] array = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(array)) != -1) {
            outputStream.write(array, 0, len);
        }
        inputStream.close();
        outputStream.close();
        return outputStream.toByteArray();
    }

}
